package com.study.zzedu.fragment.tab.catalog;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;

import com.aliyun.player.alivcplayerexpand.bean.LongVideoBean;
import com.study.zzedu.R;
import com.study.zzedu.base.BaseFragment;
import com.study.zzedu.bean.BranchNode;
import com.study.zzedu.bean.BranchViewBinder;
import com.study.zzedu.bean.LeafNode;
import com.study.zzedu.bean.LeafNode2;
import com.study.zzedu.bean.LeafViewBinder;
import com.study.zzedu.bean.LeafViewBinder2;
import com.study.zzedu.bean.RootNode;
import com.study.zzedu.bean.RootViewBinder;
import com.study.zzedu.ui.Webview_try;
import com.study.zzedu.ui.discussdetail.DiscussDetailActivity;
import com.study.zzedu.ui.exercise.activity.IntroduceItemActivity;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.ToastUtil;
import com.study.zzedu.widget.SpacesItemDecoration;
import com.study.zzedu.widget.TreeViewAdapter;
import com.study.zzedu.widget.bean.LayoutItem;
import com.study.zzedu.widget.bean.TreeNode;
import com.study.zzedu.widget.bean.TreeViewBinder;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.study.zzedu.utils.AppConstant.courseDetail;

/**
 * Created by kiros on 2020/9/5.
 * 课程页面
 */

public class CatalogFragment extends BaseFragment<CatalogContract.IView, CatalogPresenter> implements CatalogContract.IView {

    private RecyclerView rv;
    private List<TreeNode> list = new ArrayList<>();
    private TreeViewAdapter adapter;
    private LongVideoBean longVideoBean = new LongVideoBean();

    VideoSwitchChangeReceiver locationBroadcast;

    public CatalogFragment() {
    }

    @Override
    protected CatalogPresenter createPresenter() {
        return new CatalogPresenter();
    }

    @Override
    protected CatalogContract.IView createView() {
        return this;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_catalog;
    }

    RelativeLayout containerView;
    TreeNode root;

    protected void initView(View view) {
        rv = view.findViewById(R.id.rv);
        initAdapter();
        //initView2(view);
    }

    @Override
    protected void initData() {
        getPresenter().getCourseContent(getContext(), AppConstant.courseCode);

        locationBroadcast = new VideoSwitchChangeReceiver();
        IntentFilter intentFilter = new IntentFilter();
        // 2. 设置接收广播的类型
        intentFilter.addAction(AppConstant.ACTION_EVENT_VIDEO_TREE_REFRESH);
        // 3. 动态注册：调用Context的registerReceiver（）方法
        getContext().registerReceiver(locationBroadcast, intentFilter);
    }

    @Override
    protected void initListener() {
    }

    @Override
    public void getCourseContentData(String name) {
        try {
            list.clear();
            //LogUtil.i("Forget","getCourseContentData:"+name);
            LogUtil.iLongMsg(name);

            JSONObject job = new JSONObject(name);
            JSONArray jArray = job.getJSONArray("data");
            courseDetail = jArray;
            if (videoSwitchFlag) {
                com.study.zzedu.ui.AlivcPlayerActivity.setCourseList(courseDetail);
                videoSwitchFlag = false;
            }
            //第一层循环
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject job1 = jArray.getJSONObject(i);
                try {
                    TreeNode rootNode = new TreeNode<>(new RootNode(job1.getString("title")));
                    if (job1.has("children")) {
                        JSONArray jArray1 = job1.getJSONArray("children");
                        //第二层循环（二级菜单）
                        for (int y = 0; y < jArray1.length(); y++) {
                            JSONObject job2 = jArray1.getJSONObject(y);
                            //有“子”加载枝节点
                            if (job2.has("children")) {
                                TreeNode<BranchNode> branchNode1 = new TreeNode<>(new BranchNode(job2.getString("title")));
                                JSONArray jArray2 = job2.getJSONArray("children");
                                rootNode.addChild(branchNode1);
                                //第三次循环（三级菜单）----最多支持三级
                                for (int p = 0; p < jArray2.length(); p++) {
                                    JSONObject job3 = jArray2.getJSONObject(p);
                                    if (!TextUtils.isEmpty(job3.getString("title")) && !TextUtils.isEmpty(job3.getString("dataType"))) {
                                        String s = ("课件".equals(job3.getString("dataType"))) ? job3.getString("contentType") : job3.getString("dataType");
                                        TreeNode<LeafNode2> LeafNode2 = new TreeNode<>(new LeafNode2(
                                                job2.getString("title"),
                                                job3.has("url") ? job3.getString("url") : "",
                                                job3.getString("contentCode"),
                                                job3.getString("status"),
                                                job3.has("lastPosition") ? job3.getString("lastPosition") : "", s));
                                        rootNode.addChild(LeafNode2);
                                    }
                                }

                            } else {
                                if ("目录".equals(job2.getString("dataType"))) {
                                    //处理空目录情况
                                    TreeNode<BranchNode> branchNode1 = new TreeNode<>(new BranchNode(job2.getString("title")));
                                    rootNode.addChild(branchNode1);
                                } else {
                                    //无“子”加载叶节点
                                    if (!TextUtils.isEmpty(job2.getString("title")) && !TextUtils.isEmpty(job2.getString("dataType"))) {
                                        String s = ("课件".equals(job2.getString("dataType"))) ? job2.getString("contentType") : job2.getString("dataType");
                                        TreeNode<LeafNode> LeafNode = new TreeNode<>(new LeafNode(job2.getString("title"),
                                                job2.has("url") ? job2.getString("url") : "",
                                                job2.getString("contentCode"),
                                                job2.getString("status"),
                                                job2.has("lastPosition") ? job2.getString("lastPosition") : "", s));
                                        rootNode.addChild(LeafNode);
                                    }
                                }

                            }
                        }
                    }
                    list.add(rootNode);
                } catch (Exception e) {
                    e.toString();
                }
            }
            if (jArray.length() > 0) {
                getActivity().findViewById(R.id.rl_default_catalog).setVisibility(View.GONE);
                if (adapter != null) {
                    //adapter.notifyDataSetChanged();
                    adapter.notifyData(list);
                    LogUtil.i("Forget", "adapter.notifyDataSetChanged()。。。。。。。。。。。。。。。。。。。。。。:");
                }
            } else {
                return;
            }
        } catch (Exception e) {
            e.toString();
        }

    }

    @Override
    public void getURLReturn(String urlInfo) {
        try {
            JSONObject job = new JSONObject(urlInfo);
            JSONArray jArray = job.getJSONArray("data");

            if (jArray.length() > 0) {
                String job1 = jArray.get(0).toString();
                if (longVideoBean != null) {
                    longVideoBean.setSaveUrl(job1);
                    com.study.zzedu.ui.AlivcPlayerActivity.setCourseList(courseDetail, AppConstant.courseCode, AppConstant.contentCode);
                    com.study.zzedu.ui.AlivcPlayerActivity.startAlivcPlayerActivity(getActivity(), longVideoBean);
                    return;
                }
            } else {
                ToastUtil.showShortToast("播放地址获取失败");
            }
        } catch (Exception e) {
            e.toString();
        }
    }

    @Override
    public void getData(String data) {
    }

    @Override
    public void showError(String error) {
        if (null != error && !TextUtils.isEmpty(error)) {
            ToastUtil.showShortToast(error);
        }
    }


    private void initAdapter() {
        LogUtil.i("Forget", "initAdapter。。。。。。。。。。。。。。。。。。。。。。:");
        adapter = new TreeViewAdapter(list, Arrays.asList(new RootViewBinder(), new BranchViewBinder(), new LeafViewBinder(), new LeafViewBinder2())) {

            @Override
            public void toggleClick(TreeViewBinder.ViewHolder viewHolder, View view, boolean isOpen, TreeNode treeNode) {
                if (isOpen) {
                    addNewNode(treeNode);
                } else {
                    adapter.lastToggleClickToggle();
                }
            }

            @Override
            public void toggled(TreeViewBinder.ViewHolder viewHolder, View view, boolean isOpen, TreeNode treeNode) {
                viewHolder.findViewById(R.id.ivNode).setRotation(isOpen ? 90 : 0);
            }

            @Override
            public void checked(TreeViewBinder.ViewHolder viewHolder, View view, boolean checked, TreeNode treeNode) {

            }

            @Override
            public void itemClick(TreeViewBinder.ViewHolder viewHolder, View view, TreeNode treeNode) {
                String name = null;
                LayoutItem item = treeNode.getValue();
                if (item instanceof RootNode) {
                    name = ((RootNode) item).getName();
                } else if (item instanceof BranchNode) {
                    name = ((BranchNode) item).getName();
                } else if (item instanceof LeafNode) {
                    name = ((LeafNode) item).getName();
                    switch (((LeafNode) item).getDataType()) {
                        case "讨论":
                            AppConstant.contentID = ((LeafNode) item).getContentCode();
                            startActivity(new Intent(view.getContext(), DiscussDetailActivity.class));
                            break;
                        case "测试":
                            AppConstant.chapterCode = ((LeafNode) item).getContentCode();
                            Intent intent = new Intent(getContext(), IntroduceItemActivity.class);
                            startActivity(intent);
                            break;
                        case "链接":
                            AppConstant.contentCode = ((LeafNode) item).getContentCode();
                            //ToastUtil.showShortToast("是个链接。。");

                            Intent intent3 = new Intent(getContext(), Webview_try.class);
                            intent3.putExtra("url", ((LeafNode) item).getUrl());
                            intent3.putExtra("title", ((LeafNode) item).getName());
                            startActivity(intent3);
                            break;
                        case "视频":
                            AppConstant.contentCode = ((LeafNode) item).getContentCode();
                            if (longVideoBean != null) {
                                longVideoBean.setContentCode(((LeafNode) item).getContentCode());
                                longVideoBean.setTitle(((LeafNode) item).getName());
                                longVideoBean.setWatchDuration(((LeafNode) item).getLastPosition());
                            }
                            if (TextUtils.isEmpty(((LeafNode) item).getUrl())) {
                                ToastUtil.showShortToast("未找到资源");
                                return;
                            }

                            if (AppConstant.domainList != null) {
                                try {
                                    AppConstant.littleURL = ((LeafNode) item).getUrl();
                                    String url = AppConstant.domainList.getString(0) + ((LeafNode) item).getUrl();
                                    longVideoBean.setSaveUrl(url);
                                    //AppConstant.videoLineFlag = "1";
                                    com.study.zzedu.ui.AlivcPlayerActivity.setCourseList(courseDetail, AppConstant.courseCode, AppConstant.contentCode);
                                    com.study.zzedu.ui.AlivcPlayerActivity.startAlivcPlayerActivity(getActivity(), longVideoBean);
                                } catch (Exception e) {
                                    e.toString();
                                }
                            }else {
                                ToastUtil.showShortToast("AppConstant.domainList == null");
                            }
                            //getPresenter().getVideoURL(getContext(),((LeafNode) item).getUrl());
                            break;
                        default:
                            ToastUtil.showShortToast("未处理类型");
                            break;
                    }
                }
                //Toast.makeText(MainActivity34.this, name, Toast.LENGTH_SHORT).show();
            }
        };
        rv.addItemDecoration(new SpacesItemDecoration(20));
        rv.setLayoutManager(new LinearLayoutManager(getContext()));
        rv.setAdapter(adapter);
    }

    private void addNewNode(final TreeNode treeNode) {
        autoProgress(true);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                String name = null;
//                LayoutItem item = treeNode.getValue();
//                if (item instanceof RootNode) {
//                    name = ((RootNode) item).getName();
//                } else if (item instanceof BranchNode) {
//                    name = ((BranchNode) item).getName();
//                } else if (item instanceof LeafNode) {
//                    name = ((LeafNode) item).getName();
//                }
//
//                List<TreeNode> list = treeNode.getChildNodes();
//                boolean hasLeaf = false;
//                for (TreeNode child : list) {
//                    if (child.getValue() instanceof LeafNode) {
//                        hasLeaf = true;
//                        break;
//                    }
//                }
//                if (!hasLeaf) {
////                    TreeNode<LeafNode> leafNode1 = new TreeNode<>(new LeafNode(name+"新增叶1"));
////                    TreeNode<LeafNode> leafNode2 = new TreeNode<>(new LeafNode(name+"新增叶2"));
////                    treeNode.addChild(leafNode1);
////                    treeNode.addChild(leafNode2);
//                }
                autoProgress(false);
                adapter.lastToggleClickToggle();
            }
        }, 200);
    }

    private ProgressDialog progressDialog;

    private void autoProgress(boolean show) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("正在加载数据。。。");
        }
        if (show) {
            progressDialog.show();
        } else {
            progressDialog.dismiss();
        }
    }

    //视频播放页 不同视频切换flag;
    private Boolean videoSwitchFlag = false;

    class VideoSwitchChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConstant.ACTION_EVENT_VIDEO_TREE_REFRESH)) {
                LogUtil.i("Forget", "收到广播：。。。。。。。。。重新请求课程树");
                videoSwitchFlag = true;
                getPresenter().getCourseContent(getContext(), AppConstant.courseCode);
            }
        }
    }

    @Override
    public void onDestroy() {
        if (locationBroadcast != null)
            getContext().unregisterReceiver(locationBroadcast);
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
